package com.mspbots.sync.callback.services.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mspbots.sync.BaseGenericService;
import com.mspbots.sync.callback.model.CallbackAction;
import com.mspbots.sync.callback.model.CallbackMessage;
import com.mspbots.sync.callback.services.NoticeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * com.mspbots.sync.callback.services.SchedulesNoticeService
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/10/11
 */
@Log4j2
@Service(value = "schedule")
public class SchedulesNoticeServiceImpl extends BaseGenericService implements NoticeService {

    @Override
    public Mono<Void> sender(Integer tenant, CallbackMessage callbackMessage) {
        if (callbackMessage.getAction() == CallbackAction.deleted) {
            log.debug("Ticket wise send delte tenant id is:{} ,cw id is {}", tenant, callbackMessage.getId());
            ObjectNode objectNode = this.objectMapper.createObjectNode();
            objectNode.put("tenantId", tenant);
            objectNode.put("action", callbackMessage.getAction().name());
            objectNode.put("id", callbackMessage.getId());
            this.messagingTemplate.convertAndSend("msp.wise.callback.schedules", "", objectNode);
            return Mono.empty().then();
        }
        return Mono.just(callbackMessage.getEntity())
                .map(result -> {
                    try {
                        return this.objectMapper.readValue(result, JsonNode.class);
                    } catch (JsonProcessingException e) {
                        log.error("This read json is error,msg:{}", e.getMessage());
                    }
                    return this.objectMapper.createObjectNode();
                }).doOnNext(jsonNode -> {
                    ObjectNode objectNode = jsonNode.deepCopy();
                    objectNode.put("tenantId", tenant);
                    objectNode.put("action", callbackMessage.getAction().name());
                    this.messagingTemplate.convertAndSend("msp.wise.callback.schedules", "", objectNode);
                }).then();
    }

}
